<template>
  <view class="container">
    <!-- 页面标题 -->
    <!-- <view class="header">
      <text class="title">求购信息跟进</text>
    </view> -->

    <!-- 求购列表 -->
    <scroll-view :scroll-y="true" class="list-container">
      <view v-for="item in purchaseList" :key="item.purchaseId" class="purchase-card">
        <view class="info-row">
          <text class="label">求购ID：</text>
          <text class="value">{{ item.purchaseId }}</text>
        </view>

        <view class="info-row">
          <text class="label">联系人：</text>
          <text class="value clickable" @tap="togglePhoneVisible(item)">
            {{ item.contactName }} | {{ formatPhone(item.contactPhone, item.showFullPhone) }}
          </text>
        </view>

        <view class="info-row">
          <text class="label">设备类型ID：</text>
          <text class="value">{{ item.typeId }}</text>
        </view>

        <view class="info-row">
          <text class="label">品牌：</text>
          <text class="value">{{ item.brand || '不限' }}</text>
        </view>

        <view class="info-row">
          <text class="label">型号：</text>
          <text class="value">{{ item.model || '无要求' }}</text>
        </view>

        <view class="info-row">
          <text class="label">期望价格：</text>
          <text class="value">{{ formatPrice(item.expectedPrice) }}</text>
        </view>

        <view class="info-row">
          <text class="label">期望年份：</text>
          <text class="value">{{ item.expectedYear || '不限' }}</text>
        </view>

        <view class="info-row">
          <text class="label">参数要求：</text>
          <text class="value">{{ item.parameterRequirement || '无特殊要求' }}</text>
        </view>

        <view class="info-row">
          <text class="label">发布时间：</text>
          <text class="value">{{ formatTime(item.releaseTime) }}</text>
        </view>

        <!-- <view class="info-row status">
          <text class="label">跟进状态：</text>
          <text :class="'status-text status-' + item.status">{{ getStatusText(item.status) }}</text>
        </view> -->

        <!-- 操作按钮 -->
        <!-- <view class="action-buttons">
          <button v-if="item.status === 'pending'" type="primary" size="mini" @click="callBuyer(item)">联系求购人</button>
          <button v-if="item.status === 'following'" type="default" size="mini" @click="openFollowUpModal(item)">记录跟进</button>
          <button v-if="item.status === 'following'" type="primary" size="mini" @click="recommendDevice(item)">推荐设备</button>
          <button v-if="item.status === 'matched'" type="default" size="mini" @click="openTransactionModal(item)">记录交易进展</button>
          <button v-if="['completed', 'cancelled'].includes(item.status)" type="warn" size="mini" @click="viewHistory(item)">查看记录</button>
        </view> -->
      </view>

      <view v-if="purchaseList.length === 0" class="empty-tip">暂无求购信息</view>
    </scroll-view>

    <!-- 弹窗遮罩 -->
    <view class="popup-mask" v-if="showModal" @click="closeAllModals"></view>

    <!-- 1. 记录跟进弹窗 -->
    <view class="popup-dialog" v-if="showFollowUp">
      <view class="popup-title">记录跟进</view>
      <textarea class="popup-textarea" v-model="followUpContent" placeholder="请输入沟通内容..." />
      <view class="popup-actions">
        <button class="btn-cancel" @click="closeAllModals">取消</button>
        <button class="btn-confirm" @click="saveFollowUp">确定</button>
      </view>
    </view>

    <!-- 2. 交易结果弹窗 -->
    <view class="popup-dialog" v-if="showTransaction">
      <view class="popup-title">记录交易结果</view>
      <radio-group @change="onTransactionChange">
        <label class="radio-item" v-for="opt in transactionOptions" :key="opt.value">
          <radio :value="opt.value" :checked="selectedResult === opt.value" />
          <text>{{ opt.label }}</text>
        </label>
      </radio-group>
      <textarea
        v-if="selectedResult === 'cancelled'"
        class="popup-textarea mt-10"
        v-model="cancelReason"
        placeholder="请输入失败原因"
      />
      <view class="popup-actions mt-15">
        <button class="btn-cancel" @click="closeAllModals">取消</button>
        <button class="btn-confirm" @click="submitTransaction">提交</button>
      </view>
    </view>

    <!-- 3. 历史记录弹窗（底部滑出） -->
    <view class="popup-bottom" v-if="showHistory">
      <view class="popup-title">跟进与交易记录</view>
      <scroll-view scroll-y class="history-list">
        <view v-for="(log, i) in historyLogs" :key="i" class="log-item">
          <text class="time">{{ log.time }}</text>
          <text class="desc">{{ log.content }}</text>
        </view>
      </scroll-view>
      <button class="close-btn" @click="closeAllModals">关闭</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow} from '@dcloudio/uni-app'
//导入接口
import {selectBusinessId ,updateStatus} from '../../../services/PurchaseDemand'
//导入类型
import type { PurchaseDemand } from '../../../types/PurchaseDemand'
// -------------------------------
// 🔧 类型定义（仅用于说明，TS需.d.ts）
// -------------------------------

/**
 * @typedef {Object} PurchaseDemand
 * @property {number|null} purchaseId - 求购信息唯一标识
 * @property {number|null} userId - 用户ID
 * @property {number|null} typeId - 设备类型ID
 * @property {string|null} brand - 品牌
 * @property {string|null} model - 型号
 * @property {number|null} expectedPrice - 期望价格（元）
 * @property {number|null} expectedYear - 期望年份
 * @property {string|null} parameterRequirement - 参数要求
 * @property {string|null} contactName - 联系人姓名
 * @property {string|null} contactPhone - 联系电话
 * @property {0|1|2|3} purchaseStatus - 求购状态
 * @property {number|null} businessmanId - 业务员ID
 * @property {string|null} releaseTime - 发布时间 (ISO)
 * @property {string|null} createTime - 创建时间
 * @property {string|null} updateTime - 更新时间
 */

// -------------------------------
// 📦 数据与状态
// -------------------------------

const showModal = ref(false)
const showFollowUp = ref(false)
const showTransaction = ref(false)
const showHistory = ref(false)

const currentPurchase = ref(null)
//记录文本
const followUpContent = ref('')
//状态
const selectedResult = ref('completed')
//请输入失败原因
const cancelReason = ref('')
//文本集合
const historyLogs = ref([])

//
const rawPurchaseList = ref<PurchaseDemand[]>()
const purchaseList = ref<any[]>([])
const transactionOptions = [
  { label: '交易成功', value: 'completed' },
  { label: '交易失败', value: 'cancelled' }
]

// 模拟后端返回的数据（符合 PurchaseDemand 结构）
onLoad(async() => {
  const res=await selectBusinessId();
  rawPurchaseList.value=res.data.list
  console.log('用户求购信息', rawPurchaseList.value)
  // 映射为页面可用数据（添加 UI 字段）
 purchaseList.value = rawPurchaseList.value.map(item => ({
    ...item,
    showFullPhone: false,
    logs: [],
    status: mapStatusToFollowUp(item.purchaseStatus)
  }))
})



// -------------------------------
// 🔄 工具函数
// -------------------------------

// 状态码 → UI 状态
function mapStatusToFollowUp(status) {
  switch (status) {
    case 0: return 'pending'
    case 1: return 'following'
    case 2: return 'completed'
    case 3: return 'cancelled'
    default: return 'pending'
  }
}

// 格式化手机号
const formatPhone = (phone, showFull) => {
  if (!phone) return '—'
  if (showFull) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 切换电话显示
const togglePhoneVisible = (item) => {
  item.showFullPhone = !item.showFullPhone
}

// 格式化价格（元 → 万元）
const formatPrice = (price) => {
  if (!price) return '面议'
  return `${Math.round(price / 10000)} 万元`
}

// 格式化时间 ISO → YYYY-MM-DD HH:mm
const formatTime = (isoString) => {
  if (!isoString) return '—'
  const date = new Date(isoString)
  const Y = date.getFullYear()
  const M = String(date.getMonth() + 1).padStart(2, '0')
  const D = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const m = String(date.getMinutes()).padStart(2, '0')
  return `${Y}-${M}-${D} ${h}:${m}`
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待联系',
    following: '跟进中',
    matched: '已匹配',
    completed: '已成交',
    cancelled: '已取消'
  }
  return map[status] || '未知'
}

// -------------------------------
// 📞 核心交互逻辑
// -------------------------------

// 拨打电话
const callBuyer = (item) => {
  uni.makePhoneCall({
    phoneNumber: item.contactPhone,
    success: () => {
      item.logs.unshift({
        time: formatTime(new Date().toISOString()),
        content: `已联系求购人 ${item.contactName}`
      })
      item.status = 'following'
      uni.showToast({ title: '已更新为跟进中', icon: 'none' })
    },
    fail: () => {
      uni.showToast({ title: '通话失败', icon: 'error' })
    }
  })
}

// 打开跟进弹窗
const openFollowUpModal = (item) => {
  currentPurchase.value = item
  followUpContent.value = ''
  showFollowUp.value = true
  showModal.value = true
}

// 保存跟进
const saveFollowUp = () => {
  if (!followUpContent.value.trim()) {
    uni.showToast({ title: '请输入跟进内容', icon: 'none' })
    return
  }
  currentPurchase.value.logs.unshift({
    time: formatTime(new Date().toISOString()),
    content: `【跟进】${followUpContent.value.trim()}`
  })
  closeAllModals()
}

// 推荐设备
const recommendDevice = (item) => {
  uni.showActionSheet({
    itemList: ['确认推荐'],
    success: () => {
      item.logs.unshift({
        time: formatTime(new Date().toISOString()),
        content: '已向客户推荐匹配设备。'
      })
      item.status = 'matched'
      uni.showToast({ title: '已推荐设备', icon: 'success' })
    }
  })
}

// 打开交易弹窗
const openTransactionModal = (item) => {
  currentPurchase.value = item
  selectedResult.value = 'completed'
  cancelReason.value = ''
  showTransaction.value = true
  showModal.value = true
}

// 选择交易结果
const onTransactionChange = (e) => {
  selectedResult.value = e.detail.value
}

// 提交交易结果
const submitTransaction = () => {
  const now = formatTime(new Date().toISOString())
  if (selectedResult.value === 'completed') {
    currentPurchase.value.logs.unshift({
      time: now,
      content: '客户确认购买，交易成功完成。'
    })
    currentPurchase.value.status = 'completed'
    currentPurchase.value.purchaseStatus = 2
  } else {
    currentPurchase.value.logs.unshift({
      time: now,
      content: `交易失败，原因：${cancelReason.value || '未填写'}`
    })
    currentPurchase.value.status = 'cancelled'
    currentPurchase.value.purchaseStatus = 3
  }
  closeAllModals()
  uni.showToast({ title: '已提交结果' })
}

// 查看历史记录
const viewHistory = (item) => {
  historyLogs.value = item.logs
  showHistory.value = true
  showModal.value = true
}

// 关闭所有弹窗
const closeAllModals = () => {
  showFollowUp.value = false
  showTransaction.value = false
  showHistory.value = false
  showModal.value = false
}

</script>

<style scoped>
/* 通用 */
page {
  background-color: #f8f8f8;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.list-container {
  flex: 1;
  padding: 20rpx;
}

.purchase-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
}

.info-row {
  display: flex;
  margin-bottom: 16rpx;
  font-size: 28rpx;
  color: #555;
}

.label {
  color: #888;
  width: 180rpx;
}

.value {
  flex: 1;
  color: #333;
}

.clickable {
  color: #007aff;
}

.status .value {
  font-weight: bold;
}

.status-text {
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.status-pending { background-color: #fff3cd; color: #856404; }
.status-following { background-color: #d1ecf1; color: #0c5460; }
.status-matched { background-color: #d4edda; color: #155724; }
.status-completed { background-color: #d1ecf1; color: #0c5460; }
.status-cancelled { background-color: #f8d7da; color: #721c24; }

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
  margin-top: 20rpx;
  flex-wrap: wrap;
}

.empty-tip {
  text-align: center;
  color: #999;
  margin-top: 100rpx;
  font-size: 28rpx;
}

/* ========== 弹窗样式 ========== */

.popup-mask {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.popup-dialog {
  position: fixed;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  z-index: 1000;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20rpx;
}

.popup-textarea {
  width: 100%;
  height: 150rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #fafafa;
  box-sizing: border-box;
}

.popup-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  margin-top: 30rpx;
}

.btn-cancel {
  font-size: 28rpx;
  color: #333;
}

.btn-confirm {
  font-size: 28rpx;
  background-color: #007aff;
  color: #fff;
}

.mt-10 { margin-top: 20rpx; }
.mt-15 { margin-top: 30rpx; }

/* ========== 底部弹窗 ========== */

.popup-bottom {
  position: fixed;
  bottom: 0; left: 0; right: 0;
  height: 70vh;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 30rpx;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.history-list {
  flex: 1;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
  max-height: 60vh;
}

.log-item {
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx dashed #eee;
}

.log-item .time {
  display: block;
  font-size: 24rpx;
  color: #888;
  margin-bottom: 8rpx;
}

.log-item .desc {
  font-size: 28rpx;
  color: #444;
  line-height: 1.5;
}

.close-btn {
  margin-top: 30rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 10rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  margin: 15rpx 0;
}
</style>